﻿#include "socket.h"

Socket::Socket(unsigned short port)
{
    //emit GlobalSignals::instance().Print("");
    m_tcp=new QTcpServer(this);
    for(int i=0;i<10;i++)
    {
        serversocket[i]=nullptr;

    }
    ListenIn(port);
    //如果有新的连接
    connect(m_tcp,&QTcpServer::newConnection,this,[=]()//
    {
        //创建一个新的套接字对象
        // serversocket = new QTcpSocket(this);
        for(int i=0;i<10;i++)
        {
            if(serversocket[i]==nullptr)
            {
                serversocket[i] = m_tcp->nextPendingConnection();
                config.WriteInfo(QString("创建一个新的套接字对象,请求端口：%1").arg(serversocket[i]->localPort()));
                //发送消息同步
                for(int k=1;k<26;k++)
                {
                    if(IsUdisk[k]!="")
                    {
                        config.WriteInfo(QString("创建一个新的套接字对象,重传的串口：%1").arg(k));
                        QThread::msleep(1000);
                        emit GlobalSignals::instance().ThreadUpload(k+100,"","");
                    }
                }
                //读取数据
                connect(serversocket[i],&QTcpSocket::readyRead,this,[=]()
                {
                    //config.WriteInfo(QString("服务端读取数据"));
                    qDebug() << "服务端读取数据" ;
                    QByteArray data =serversocket[i]->readAll();
                    //ui->lineEdit_18->setText(data);
                    qDebug()<<data;
                    config.WriteInfo(data);
                    // 将 QByteArray 转换为 QString
                    QString dataString = QString::fromUtf8(data);
                    QStringList json_objects = dataString.split("end\n", QString::SkipEmptyParts);
                    if (!json_objects.isEmpty()) {

                        // 遍历选中的路径
                        for (const QString& json_obj_str : json_objects) {

                            // 解析JSON字符串
                            config.WriteInfo(QString("json_obj_str=%1").arg(json_obj_str));
                            QJsonDocument parsedJson = QJsonDocument::fromJson(json_obj_str.toUtf8());
                            QJsonObject parsedObject = parsedJson.object();

                            // 从解析后的JSON对象中获取值
                            int ParentID = parsedObject["ParentID"].toInt();
                            int SubID = parsedObject["SubID"].toInt();

                            switch (ParentID) {
                            case ACQUISITION_STATION:
                            {
                                switch (SubID)
                                {
                                case HEARTBEAT_C:
                                {
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    config.WriteInfo("HEARTBEAT_C");
                                    thread->PushTask(TNOTICE);//加入线程去请求
                                    break;
                                }
                                case INTERFACE_MAPPING_C:
                                {
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    QString UserID = parsedAddress["UserID"].toString();
                                    QString Password = parsedAddress["Password"].toString();

                                    LoginInfo threadinfo;
                                    threadinfo.Indet=INTERFACEMAPPING;
                                    threadinfo.SerialportNum=0;
                                    threadinfo.UserID=UserID;
                                    threadinfo.Password=Password;//UserID
                                    threadinfo.Identnumber="";//标识号
                                    config.WriteInfo("INTERFACE_MAPPING_C");
                                    thread->PushTask(threadinfo);//加入线程去请求
                                    break;
                                }
                                case CANCEL_UPLOAD:
                                {
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    int SerialportNum = parsedAddress["SerialportNum"].toInt();
                                    config.WriteInfo(QString("CANCEL_UPLOAD=%1").arg(SerialportNum));
                                    config.IsUpload[SerialportNum]=false;
                                    //
                                    break;
                                }
                                case LOCK_LABEL_C:
                                {
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    QString UserID = parsedAddress["UserID"].toString();
                                    QString Password = parsedAddress["Password"].toString();

                                    LoginInfo threadinfo;
                                    threadinfo.Indet=LOCKLABEL;
                                    threadinfo.SerialportNum=0;
                                    threadinfo.UserID=UserID;
                                    threadinfo.Password=Password;//UserID
                                    threadinfo.Identnumber="";//标识号
                                    config.WriteInfo("LOCKLABEL");
                                    thread->PushTask(threadinfo);//加入线程去请求
                                    break;
                                }
                                case INTERFACE_QUERY_C:
                                {
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    QString UserID = parsedAddress["UserID"].toString();
                                    QString Password = parsedAddress["Password"].toString();

                                    LoginInfo threadinfo;
                                    threadinfo.Indet=QUERY;
                                    threadinfo.SerialportNum=0;
                                    threadinfo.UserID=UserID;
                                    threadinfo.Password=Password;//UserID
                                    threadinfo.Identnumber="";//标识号
                                    config.WriteInfo("QUERY");
                                    thread->PushTask(threadinfo);//加入线程去请求
                                    break;
                                }
                                case INTERFACE_BACKGROUND_LOGIN_C:
                                {
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    QString UserID = parsedAddress["UserID"].toString();
                                    QString Password = parsedAddress["Password"].toString();

                                    LoginInfo threadinfo;
                                    threadinfo.Indet=BACKGROUNDLOGIN;
                                    threadinfo.SerialportNum=0;
                                    threadinfo.UserID=UserID;
                                    threadinfo.Password=Password;//UserID
                                    threadinfo.Identnumber="";//标识号
                                    config.WriteInfo("BACKGROUNDLOGIN");
                                    thread->PushTask(threadinfo);//加入线程去请求
                                    break;
                                }

                                case INTERFACE_MAPPING_EXIT_C:
                                {
                                    thread->PushTask(INTERFACEMAPPING_EXIT);//加入线程去请求
                                    break;
                                }
                                case INTERFACE_MAPPING_SAVE_C:
                                {
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    int Row = parsedAddress["Row"].toInt();
                                    int Column = parsedAddress["Column"].toInt();
                                    int AppointFirst = parsedAddress["AppointFirst"].toInt();

                                    InterfaceMappingInfo threadinfo;
                                    threadinfo.Indet=INTERFACEMAPPING_SAVE;
                                    threadinfo.Row=Row;
                                    threadinfo.Column=Column;
                                    threadinfo.AppointFirst=AppointFirst;
                                    config.WriteInfo("INTERFACE_MAPPING_SAVE_C");
                                    thread->PushTask(threadinfo);//加入线程去请求
                                    break;
                                }
                                case INTERFACE_SELECTED_PORT_C://选中串口
                                {
                                    qDebug()<<"INTERFACE_SELECTED_PORT_C";
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    int Row = parsedAddress["Row"].toInt();
                                    int Column = parsedAddress["Column"].toInt();

                                    NewSerialportNum=1;
                                    TemporaryPath.clear();
                                    for(int i=1;i<=SYSTEMROW*SYSTEMLIST;++i)
                                    {
                                        IsInitalize[i]=false;//重新已经初始化
                                        IsALLlist[i]=false;//重新

                                        //TemporaryPath[i]="";
                                    }
                                    for (int x = 1; x <= Row; x++) {
                                        for (int y = 1; y <= Column; y++) {
                                            int number = (x - 1) * 5 + y;  // 计算当前格子的数字
                                            IsInitalize[number]=true;
                                        }
                                    }

                                    break;
                                }
                                case UPLOAD_LOGIN_C:
                                {
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    QString UserID = parsedAddress["UserID"].toString();
                                    QString Password = parsedAddress["Password"].toString();
                                    QString Identnumber = parsedAddress["IdentNumber"].toString();
                                    int serialportnum=parsedAddress["SerialportNum"].toInt();
                                    LoginInfo threadinfo;
                                    threadinfo.Indet=TUPLOAD_LOGIN;
                                    threadinfo.SerialportNum=serialportnum;
                                    threadinfo.UserID=UserID;
                                    threadinfo.Password=Password;//UserID
                                    threadinfo.Identnumber=Identnumber;//标识号
                                    config.WriteInfo("TUPLOAD_LOGIN");
                                    thread->PushTask(threadinfo);//加入线程去请求
                                    break;
                                }
                                case POLICE_MODE_C:
                                {
                                    config.WriteInfo("POLICE_MODE_C");
                                    thread->PushTask(EPARTMENT_FILE_QUERY);//加入线程去请求
                                    break;
                                }
                                case POLICE_SITUATION_INQUIRY_C:
                                {
                                    //QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    WarnInstanInfo WIndo;
                                    WIndo.Indet=POLICE_SITUATION_INQUIRY;
                                    WIndo.StartTime = parsedAddress["StartTime"].toString();
                                    WIndo.EndTime = parsedAddress["EndTime"].toString();
                                    WIndo.UserID = parsedAddress["UserID"].toString();
                                    int Index = parsedAddress["Index"].toInt();
                                    if(Index>0)
                                    {
                                        WIndo.ID=DepartmentName[Index-1].ID;
                                        WIndo.Name=DepartmentName[Index-1].Name;
                                    }
                                    config.WriteInfo("POLICE_SITUATION_INQUIRY_C");
                                    thread->PushTask(WIndo);//加入线程去请求
                                    break;
                                }
                                case  POLICE_SITUATION_UPLOAD_C:
                                {
                                    QJsonObject parsedAddress = parsedObject["Data"].toObject();
                                    // 从QJsonObject中获取特定字段的值

                                    SerialPort = parsedAddress["SerialPort"].toInt();
                                    fileallsize[SerialPort]=parsedAddress["file_AllSize"].toInt();
                                    QJsonArray jsonPoliceInfo = parsedAddress["Bind_list"].toArray();
                                    config.WriteInfo("POLICE_SITUATION_UPLOAD_C");
                                    for (const QJsonValue& category : jsonPoliceInfo) {
                                        QJsonObject categoryObject = category.toObject();
                                        BindingInfo BInfo;
                                        BInfo.SerialPort=SerialPort;
                                        BInfo.lastModified=categoryObject["lastModified"].toString();
                                        BInfo.fileSize=categoryObject["file_size"].toInt();
                                        BInfo.case_number=categoryObject["case_number"].toString();
                                        BInfo.trafficCaseTable=categoryObject["trafficCaseTable"].toString();
                                        BInfo.file_type_id=categoryObject["file_type_id"].toString();
                                        BInfo.fileName=categoryObject["fileName"].toString();
                                        BInfo.sourceFilePath=categoryObject["sourceFilePath"].toString();
                                        config.WriteInfo("POLICE_SITUATION_UPLOAD_C1");
                                        BindList.push_back(BInfo);
                                    }
                                    emit GlobalSignals::instance().ThreadBandingUpload(SerialPort);
                                    break;
                                }
                                case   POLICE_SITUATION_SKIP_C:
                                {
                                    NextInit();
                                    break;
                                }
                                case   INTERFACE_SWITCH_C:
                                {
                                    if(config.PortNum.toInt()>25)
                                    {
                                          config.WriteInfo("INTERFACE_SWITCH_C");
                                        IsSwitch=true;
                                        NewSerialportNum=1;
                                        //NextInit();
                                        emit GlobalSignals::instance().SendMessageNotifica(ACQUISITION_STATION,INTERFACE_SWITCH_S,SUCCESS);
                                    }
                                    break;
                                }
                                default:
                                {

                                    break;
                                }
                                }

                                break;
                            }
                            default:
                            {
                                break;
                            }

                            }


                        }
                    }

                });
                connect(serversocket[i], &QTcpSocket::disconnected, this,[=]()
                {
                    config.WriteInfo("服务端断开连接");
                    serversocket[i]->close();
                    serversocket[i]=nullptr;
                    //serversocket->deleteLater();
                    //qDebug()<<"服务端断开连接";

                });
                connect(serversocket[i], &QAbstractSocket::bytesWritten, [=](qint64 bytes) {
                    config.WriteInfo(QString("发送数据成功，字节大小为：%1").arg(bytes));
                    // qDebug() << bytes << " bytes written. Message sent successfully.";
                });
                connect(serversocket[i], static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this,[=]()
                {
                    config.WriteInfo(QString("服务端出现错误：%1").arg(serversocket[i]->errorString()));

                });
                break;
            }
        }
    });
}
void Socket::ListenIn(unsigned short port)
{
    //监听
    //unsigned short port=port;//
    for(int i=0;i<10;i++)
    {
        if(serversocket[i]!=nullptr)
        {
            if (serversocket[i]->state() == QAbstractSocket::ConnectedState) {
                serversocket[i]->disconnectFromHost(); // 服务端主动断开连接
                //                serversocket[i]->close(); // 关闭套接字并释放本地端口
                //                serversocket[i]==nullptr;
            }
        }
    }
    //on_pushButton_13_clicked();//客户端
    m_tcp->close();
    m_tcp->listen(QHostAddress::Any,port);//监听服务端端口
    return;

}
bool Socket::Send(int ParentID,int SubID,QJsonObject Data)
{
    // 创建一个包含嵌套子结构的JSON对象
    QJsonObject jsonObject;
    jsonObject["ParentID"] = ParentID;
    jsonObject["SubID"] = SubID;
    jsonObject["Data"] = Data;
    // 将JSON对象转换为JSON文档
    QJsonDocument jsonDocument(jsonObject);

    // 将JSON文档转换为格式化的JSON字符串
    QByteArray jsonByteArray = jsonDocument.toJson(QJsonDocument::Indented);
    jsonByteArray+="end\n";
    if(SubID!=UPDATE_CONTROL_S)
    {
        qDebug() << "QByteArray:" << jsonByteArray;
    }
    for(int i=0;i<10;i++)
    {
        if(serversocket[i]!=nullptr)
        {
            //发送数据
            if (serversocket[i]->state() == QAbstractSocket::ConnectedState) {
                serversocket[i]->write(jsonByteArray);
                config.WriteInfo("发送数据");
            }
            else {
                config.WriteInfo("未建立连接，请先建立连接。");
                // 执行连接建立的逻辑，或者给出错误提示
            }
        }
    }
    return true;
}
